package com.songmao.pricecloudapitest.utils;

import com.zf.zson.ZSON;
import com.zf.zson.exception.ZsonException;
import com.zf.zson.result.ZsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Remy
 * @description : 解析JSON
 * @date 2020-04-03 17:27
 */

public class ParsingJson {

    private ZsonResult zr;

    public ParsingJson(String json) {

        zr = ZSON.parseJson(json);
    }

    /**
     * @description: 给定一个json，在给定一个路径；则返回对应的value;没有则返回null
     * @Param path, json
     * @return: Object
     * @author: Remy
     * @time: 2020/4/3 17:35
     */
    public static Object getPathCode(String json, String path) {
        try {
            ZsonResult zr = ZSON.parseJson(json);
            return zr.getValue(path);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @description: 给定一个json，在给一个路径;返回所有的值; 没有则抛出异常
     * @return: List<Object>
     * @author: Remy
     * @time: 2020/4/3 17:36
     */
    public static List<Object> getPathCodes(String json, String path) {
        try {
            ZsonResult zr = ZSON.parseJson(json);
            return zr.getValues(path);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }


    /**
     * @description: 判断json路径是否存在
     * @return: boolean
     * @author: Remy
     * @time: 2020/4/3 17:29
     */

    public static List<String> getPaths(String json) {
        try {
            ZsonResult zr = ZSON.parseJson(json);
            return zr.getPaths();
        } catch (ZsonException e) {
            return null;
        }

    }

    public static String update(String json, String key, Object vaue) {
        ZsonResult zr = ZSON.parseJson(json);
        zr.updateValue(key, vaue);
        return zr.getValue().toString();
    }

    public ParsingJson updates(String key, Object vaue) {
        zr.updateValue("//" + key, vaue);
        return this;
    }

    public Object toJsonString() {
        return zr.getValue();
    }

    public static boolean judgmentJson(String json) {
        try {
            ZSON.parseJson(json);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


}
